import { defineStore } from 'pinia';
import { ref } from 'vue';
import api from '@/api';

export const useUserStore = defineStore('user', () => {
  const preferences = ref(null);
  const categories = ref([]);
  
  /**
   * 获取用户偏好设置
   */
  async function fetchPreferences() {
    try {
      const response = await api.get('/user/preferences');
      preferences.value = response.data.data;
      return preferences.value;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 更新用户偏好设置
   */
  async function updatePreferences(data) {
    try {
      const response = await api.put('/user/preferences', data);
      preferences.value = response.data.data;
      return preferences.value;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 获取分类列表
   */
  async function fetchCategories() {
    try {
      const response = await api.get('/user/categories');
      categories.value = response.data.data;
      return categories.value;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 创建分类
   */
  async function createCategory(data) {
    try {
      const response = await api.post('/user/categories', data);
      categories.value.push(response.data.data);
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 更新分类
   */
  async function updateCategory(id, data) {
    try {
      const response = await api.put(`/user/categories/${id}`, data);
      const index = categories.value.findIndex(c => c.id === id);
      if (index !== -1) {
        categories.value[index] = { ...categories.value[index], ...data };
      }
      return response.data.data;
    } catch (error) {
      throw error;
    }
  }
  
  /**
   * 删除分类
   */
  async function deleteCategory(id) {
    try {
      await api.delete(`/user/categories/${id}`);
      categories.value = categories.value.filter(c => c.id !== id);
    } catch (error) {
      throw error;
    }
  }
  
  return {
    preferences,
    categories,
    fetchPreferences,
    updatePreferences,
    fetchCategories,
    createCategory,
    updateCategory,
    deleteCategory,
  };
});


